import {
  asyncRouterMap,
  constantRouterMap,
} from '@/config/router.config';
import {
  getBtn,
} from '@/api/login';
import '@/public-path';
import actions from '@/actions';
import store from '@/store';
import { BlankLayout } from '@/layouts';
import marketManagementrRouter from '@/config/modules/marketManagementrRouter';
import RouteView from '@/components/publicRouters/publicRouters.vue';
import { marketManagement } from '@/core/icons';

/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
function hasPermission(permission, route, topath) {
  // if (route.meta) {
  //   let flag = false
  //   for (let i = 0, len = permission.length; i < len; i++) {
  //     if (permission[i].path === route.name) {

  //       flag = true
  //       route.meta.menuId = permission[i].menuId

  //     } else {

  //       flag = false
  //     }

  //     // flag = route.meta.permission.includes(permission[i])
  //     if (flag) {
  //       return true
  //     }
  //   }
  //   return false
  // }
  return true;
}

/**
 * 单账户多角色时，使用该方法可过滤角色不存在的菜单
 *
 * @param roles
 * @param route
 * @returns {*}
 */
// eslint-disable-next-line
function hasRole(roles, route) {
  if (route.meta && route.meta.roles) {
    return route.meta.roles.includes(roles.id);
  } else {
    return true;
  }
}

var pathNow = '';

function filterAsyncRouter(routerMap, roles, topath) {
  const accessedRouters = [];
  var topath = topath;
  routerMap.forEach(route => {
      const tmp = {
        ...route,
      };
      if (hasPermission(roles, tmp, topath)) {
        if (tmp.path == topath) {
          pathNow = tmp.path;
        }

        if (tmp.children && tmp.children.length) {
          tmp.children = filterAsyncRouter(tmp.children, roles, topath);
        }
        // if (tmp.redirect && tmp.redirect!='/home') {
        //   tmp.redirect=tmp.children&&tmp.children[0]&&tmp.children[0].path;
        // }
        accessedRouters.push(tmp);
      }
    },
  );

// const accessedRouters = routerMap.filter(route => {
//   //   const tmp = {
//   //     ...route
//   //   }
//   if (hasPermission(roles, route)) {
//     if (route.children && route.children.length) {
//       route.children = filterAsyncRouter(route.children, roles)
//     }
//     return true
//   }
//   return false
// })
  return accessedRouters;
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    original: [],
    btnPermission: {},
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers;
      state.routers = constantRouterMap.concat(routers);
    },
    SET_original: (state, routers) => {
      state.original = routers;
    },
    SET_BTN: (state, data) => {
      console.log('btnPermission', data);
      state.btnPermission = data;
    },
  },
  actions: {
    GenerateRoutes({
                     commit,
                   }, {
                     roles,
                     topath,
                   }) {
      // var asyncRouterMaps =JSON.parse(JSON.stringify(asyncRouterMap))
      return new Promise(resolve => {
        // const asyncRouterMaps = Object.assign([],asyncRouterMap)
        let accessedRouters = [];
        if (window.__POWERED_BY_QIANKUN__) {
          // 监测state变化
          actions.onGlobalStateChange((state, prev) => {
            state.routers.forEach(item => {
              let component = item.component;
              accessedRouters.push({
                path: item.path.slice(item.path.indexOf('/', 1)),
                name: item.name,
                hidden: item.hidden,
                component: () => import('@/views' + component + '.vue'),
                meta: {
                  title: item.title,
                },
              });
            });
          }, true);
        } else {
          accessedRouters = filterAsyncRouter(asyncRouterMap, roles, topath);
        }
        accessedRouters.push({
          path: '*',
          redirect: '/404',
          hidden: true,
        });
        commit('SET_original', accessedRouters);
        commit('SET_ROUTERS', accessedRouters);
        resolve({
          path: pathNow,
        });
      });
    },
    btnPermission({
                    commit,
                  }, menuId) {
      return new Promise((resolve, reject) => {
        // console.log('to',commit);
        getBtn(menuId).then(res => {
          let btn = {};
          res.forEach(item => {
            btn[item.path] = true;
          });
          commit('SET_BTN', btn);
          console.log('btnPermission', res, btn);
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },
  },
};

export default permission;